package com.jifeng.sterilizer.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jifeng.sterilizer.entity.*;
import com.jifeng.sterilizer.service.DeviceService;
import com.jifeng.sterilizer.service.FarmService;
import com.jifeng.sterilizer.service.UserControllerService;
import com.jifeng.sterilizer.utils.*;
import com.jifeng.sterilizer.vo.ControllerEntityVo;
import com.jifeng.sterilizer.vo.ControllerListVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jifeng.sterilizer.dao.ControllerDao;
import com.jifeng.sterilizer.service.ControllerService;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Service("controllerService")
@Slf4j
public class ControllerServiceImpl extends ServiceImpl<ControllerDao, ControllerEntity> implements ControllerService {

    @Autowired
    DeviceService deviceService;

    @Autowired
    UserControllerService userControllerService;

    @Autowired
    FarmService farmService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<ControllerEntity> queryWrapper = new QueryWrapper<>();
        IPage<ControllerEntity> page = this.page(
                new Query<ControllerEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    /**
     * @param params {controller_id:"1234567890"}
     * @return {code:"200",msg:"成功",data:{info:{中控器数据},list:[中控绑定消毒机数据{number,name}]}} {code:"400",msg:"失败",data:null}
     */

    @Override
    public R getInfo(Map<String, Object> params) {
        try {
            Map<String, Object> map0 = new HashMap<>();
            Object controller_id = params.get("controller_id");
            if (!RegexUtils.isNumber(String.valueOf(controller_id), 2)) {
                log.warn("方法：{}，错误信息：{}", "获取中控器信息", "中控器编号格式错误");
                return R.error(400, "中控器编号格式错误");
            }
            ControllerEntity controllerEntity = this.getOne(new QueryWrapper<ControllerEntity>().eq("number", controller_id), false);
            if (controllerEntity == null) {
                log.warn("方法：{}，错误信息：{}", "获取中控器信息", "中控器编号无效");
                return R.error(400, "中控器编号无效");
            }
            String devices = controllerEntity.getDevices();
            List<Map<String, Object>> mapList = new ArrayList<>();
            if (StringUtils.isEmpty(devices)) {
                log.warn("方法：{}，错误信息：{}", "获取中控器信息", "中控器中消毒机编号为空");
                map0.put("info", controllerEntity);
                map0.put("list", mapList);
                return R.ok().put("data", map0);
            }
            int indexOf = devices.indexOf(",");
            if (indexOf > -1) {
                String[] devicesArr = devices.split(",");
                if (devicesArr.length == 0) {
                    log.warn("方法：{}，错误信息：{}", "获取中控器信息", "中控器中消毒机编号为空");
                    return R.error(400, "中控器中消毒机编号为空");
                }
                for (String id : devicesArr) {
                    Map<String, Object> map = new HashMap<>();
                    DeviceEntity deviceEntity = deviceService.getOne(new QueryWrapper<DeviceEntity>().eq("number", id), false);
                    if (deviceEntity == null) {
                        continue;
                    }
                    Long number = deviceEntity.getNumber();
                    String name = deviceEntity.getName();
                    map.put("number", number);
                    map.put("name", name);
                    mapList.add(map);
                }
            } else {
                Map<String, Object> map = new HashMap<>();
                DeviceEntity deviceEntity = deviceService.getOne(new QueryWrapper<DeviceEntity>().eq("number", devices), false);
                if (deviceEntity == null) {
                    log.warn("方法：{}，错误信息：{}", "获取中控器信息", "中控器中消毒机编号无效");
                    return R.error(400, "中控器中消毒机编号无效");
                }
                Long number = deviceEntity.getNumber();
                String name = deviceEntity.getName();
                map.put("number", number);
                map.put("name", name);
                mapList.add(map);
            }
            map0.put("info", controllerEntity);
            map0.put("list", mapList);
            return R.ok().put("data", map0);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "获取中控器信息", e.getMessage());
            return R.error(400, "系统繁忙");
        }
    }

    private HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    public R getWXInfo(Map<String, Object> params) {
        try {
            HttpServletRequest request = getRequest();
            Integer userId = Integer.valueOf(String.valueOf(params.get("userId")));
            Map userInfo = HttpUtils.getTokenInfo(request);
            Object tokenId = userInfo.get("id");
            if (!tokenId.equals(userId)) {
                log.warn("方法：{}，错误信息：{}", "小程序接口->获取中控器信息", "只能查询本用户的数据");
                return R.error(400, "只能查询本用户的数据");
            }
            String controllerNumber = String.valueOf(params.get("controller_id"));
            if (!RegexUtils.isNumber(String.valueOf(controllerNumber), 2)) {
                log.warn("方法：{}，错误信息：{}", "小程序接口->获取中控器信息", "中控器编号格式错误");
                return R.error(400, "中控器编号格式错误");
            }
            UserControllerEntity userControllerEntity = userControllerService.getOne(new QueryWrapper<UserControllerEntity>().eq("user_id", userId).eq("controller_number", controllerNumber));
            if (userControllerEntity == null) {
                log.warn("方法：{}，错误信息：{}", "小程序接口->获取中控器信息", "该用户未绑定该中控器");
                return R.error(400, "该用户未绑定该中控器");
            }
            Map<String, Object> map = new HashMap<>();
            map.put("controller_id", userControllerEntity.getControllerNumber());
            R info = getInfo(map);
            return info;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "小程序接口->获取中控器信息", e.getMessage());
            return R.error(400, "系统繁忙");
        }
    }

    @Override
    public R mySave(ControllerEntityVo controller) {
        ControllerEntity controllerEntity = new ControllerEntity();
        BeanUtils.copyProperties(controller, controllerEntity);
        boolean save = this.save(controllerEntity);
        if (save) {
            return R.ok();
        }
        return R.error();
    }

    @Override
    public R updateByNumber(ControllerEntityVo controller) {
        Map<String, Object> errMap = new HashMap<>();
        Long number = controller.getNumber();
        ControllerEntity controllerEntity = this.getOne(new QueryWrapper<ControllerEntity>().eq("number", number));
        if (controllerEntity == null) {
            errMap.put("number", "无效的设备编号");
        }
        if (!errMap.isEmpty()) {
            return R.error().put("data", errMap);
        }
        ControllerEntity updateControllerEntity = new ControllerEntity();
        BeanUtils.copyProperties(controller, updateControllerEntity);
        boolean update = this.update(updateControllerEntity, new QueryWrapper<ControllerEntity>().eq("number", number));
        if (update) {
            return R.ok();
        }
        return R.error();
    }

    @Override
    public R add(Map<String, Object> params) {
        try {
            Object number = params.get("number");
            Object controller_type_id = params.get("controller_type_id");
            Object farm_id = params.get("farm_id");
            Object name = params.get("name");
            Object memo = params.get("memo");
            if (!RegexUtils.isNumber(number.toString(), 2)) {
                log.warn("方法：{}，错误信息：{}", "新增中控器的基本信息", "中控器编号格式错误");
                return R.error(400, "中控器编号格式错误");
            }
            ControllerEntity entity = this.getOne(new QueryWrapper<ControllerEntity>().eq("number", number), false);
            if (entity != null) {
                log.warn("方法：{}，错误信息：{}", "新增中控器的基本信息", "中控器已存在");
                return R.error(400, "中控器已存在");
            }
            ControllerEntity controllerEntity = new ControllerEntity();
            controllerEntity.setNumber(Long.valueOf(number.toString()));
            controllerEntity.setControllerTypeId(Long.valueOf(controller_type_id.toString()));
            controllerEntity.setFarmId(Long.valueOf(farm_id.toString()));
            controllerEntity.setName(name.toString());
            controllerEntity.setMemo(memo.toString());
            boolean save = this.save(controllerEntity);
            if (save) {
                return R.ok();
            }
            return R.error();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "新增中控器的基本信息", e.getMessage());
            return R.error(400, "系统繁忙");
        }

    }

    @Override
    public R myUpdate(Map<String, Object> params) {
        try {
            Object number = params.get("number");
            Object controller_type_id = params.get("controller_type_id");
            Object farm_id = params.get("farm_id");
            Object name = params.get("name");
            Object memo = params.get("memo");
            if (!RegexUtils.isNumber(number.toString(), 2)) {
                log.warn("方法：{}，错误信息：{}", "修改中控器的基本信息", "中控器编号格式错误");
                return R.error(400, "中控器编号格式错误");
            }
            ControllerEntity controllerEntity = new ControllerEntity();
            controllerEntity.setControllerTypeId(Long.valueOf(controller_type_id.toString()));
            controllerEntity.setFarmId(Long.valueOf(farm_id.toString()));
            controllerEntity.setName(name.toString());
            controllerEntity.setMemo(memo.toString());
            boolean update = this.update(controllerEntity, new UpdateWrapper<ControllerEntity>().eq("number", number));
            if (update) {
                return R.ok();
            }
            return R.error();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "修改中控器的基本信息", e.getMessage());
            return R.error(400, "系统繁忙");
        }
    }

    @Override
    public R del(Map<String, Object> params) {
        try {
            Object number = params.get("number");
            if (!RegexUtils.isNumber(number.toString(), 2)) {
                log.warn("方法：{}，错误信息：{}", "删除中控器", "中控器编号格式错误");
                return R.error(400, "中控器编号格式错误");
            }
            boolean remove = this.remove(new QueryWrapper<ControllerEntity>().eq("number", number));
            if (remove) {
                return R.ok();
            }
            return R.error();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "删除中控器", e.getMessage());
            return R.error(400, "系统繁忙");
        }

    }

    @Override
    public R changeTime(Map<String, Object> params) {
        try {
            Object number = params.get("number");
            if (!RegexUtils.isNumber(number.toString(), 2)) {
                log.warn("方法：{}，错误信息：{}", "设置中控机的销售时间", "中控器编号格式错误");
                return R.error(400, "中控器编号格式错误");
            }
            ControllerEntity controllerEntity = new ControllerEntity();
            controllerEntity.setSaleTime(new Date());
            boolean update = this.update(controllerEntity, new UpdateWrapper<ControllerEntity>().eq("number", number));
            if (update) {
                return R.ok();
            }
            return R.error();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "设置中控机的销售时间", e.getMessage());
            return R.error(400, "系统繁忙");
        }

    }

    @Override
    public R mapList() {
        try {
            // 如果登录的是农场主，让中控器中的farmId和用户中的farmId的一致
            HttpServletRequest request = getRequest();
            // 获得token中的用户信息
            Map tokenInfo = HttpUtils.getTokenInfo(request);
            Object type = tokenInfo.get("type");
            Object id = tokenInfo.get("id");
            List<ControllerEntity> controllerEntities = this.list();
            if (type.toString().equals("3")) {
                List<UserControllerEntity> userControllerEntities = userControllerService.list(new QueryWrapper<UserControllerEntity>().eq("user_id", id));
                List<ControllerEntity> collect = userControllerEntities.stream().map(userControllerEntity -> {
                    ControllerEntity controllerEntity = this.getOne(new QueryWrapper<ControllerEntity>().eq("number", userControllerEntity.getControllerNumber()));
                    return controllerEntity;
                }).collect(Collectors.toList());
                controllerEntities = collect;
            }
            List<Map<String, Object>> collect = controllerEntities.stream().map(controllerEntity -> {
                Map<String, Object> map = new HashMap<>();
                map.put("id", controllerEntity.getId());
                map.put("number", controllerEntity.getNumber());
                map.put("name", controllerEntity.getName());
                map.put("lng", controllerEntity.getLng());
                map.put("lat", controllerEntity.getLat());
                map.put("location", controllerEntity.getLocation());
                return map;
            }).collect(Collectors.toList());
            return R.ok().put("data", collect);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "获取所有中控器地理位置信息", e.getMessage());
            return R.error(400, "系统繁忙");
        }

    }

    @Override
    public R getDetail(Map<String, Object> params) {
        try {
            Object id = params.get("id");
            ControllerEntity controllerEntity = this.getById((Serializable) id);
            return R.ok().put("data", controllerEntity);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方法：{}，错误信息：{}", "获取中控器的详情信息 PC", e.getMessage());
            return R.error(400, "系统繁忙");
        }
    }
}